﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data;
using DataAccess;

namespace iEN.Immediate
{
    public partial class ShowNowSys : System.Web.UI.Page
    {
        DataAccess.DBAccess DBAPI = new DataAccess.DBAccess();
        DataAccess.WebService WSAPI = new DataAccess.WebService();

        protected void Page_Load(object sender, EventArgs e)
        {
             

            if (this.Page.Request.QueryString["ID"] != null)
            {
                string strID = this.Page.Request.QueryString["ID"];

                //Create the Row
                //GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                ////Add the two Columns
                //row.Cells.AddRange(CreateCells());
                //gvMain.Parent.Controls.Add(row);

                if (strID == "-1")
                    strID = "0";


                DataTable dtOrg = DBAPI.getOrgGroupTable("1");

                Session["dtOrg"] = dtOrg;

                dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
                dtOrg = dtOrg.DefaultView.ToTable();

                if (dtOrg.Rows.Count < 1)
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "無任何大樓";
                }

                else
                {
                    lblMsg.Visible = false;
                    Table tbMain = new Table();
                    int iRow = (dtOrg.Rows.Count / 5) + 1;
                    int iMod = dtOrg.Rows.Count % 5;
                    for (int i = 1; i <= iRow; i++)
                    {
                        if (i == iRow)
                        {
                            TableRow tbrM1 = new TableRow();

                            for (int j = 0; j < iMod; j++)
                            {
                                tbrM1.Cells.Add(CreateCells(dtOrg.Rows[(i - 1) * 5 + j]["_id"].ToString(), i, j));
                            }
                            tbMain.Rows.Add(tbrM1);
                           
                        }
                        else
                        {
                            TableRow tbrM1 = new TableRow();

                            for (int j = 0; j < 5; j++)
                            {
                                tbrM1.Cells.Add(CreateCells(dtOrg.Rows[(i - 1) * 5 + j]["_id"].ToString(), i, j));
                            }
                            tbMain.Rows.Add(tbrM1);
                        }
                    }
                    Panel1.Controls.Add(tbMain);
                }
                
               
            }
        }

        private TableCell CreateCells(string strID, int i, int j)
        {

            DataTable dtOrg = (DataTable)Session["dtOrg"];

            dtOrg.DefaultView.RowFilter = "_id ='" + strID + "'";
            DataTable dtBuilding = dtOrg.DefaultView.ToTable();

            dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
            DataTable dtFloor = dtOrg.DefaultView.ToTable();

            DataTable dtDevice = DBAPI.getDeviceTable("1");


            int iRoomCnt = 0;
            int iMeter = 0;
            for (int n = 0; n < dtFloor.Rows.Count; n++)
            {
                dtOrg.DefaultView.RowFilter = "_parent_id ='" + dtFloor.Rows[n]["_id"].ToString()+ "'";
                DataTable dtRoom = dtOrg.DefaultView.ToTable();
                iRoomCnt = iRoomCnt + dtRoom.Rows.Count;

                for (int m = 0; m < dtRoom.Rows.Count; m++)
                {
                    DataTable dtMeter = dtDevice.Copy();
                    dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[m]["_id"].ToString() + "'";
                    dtMeter = dtMeter.DefaultView.ToTable();
                    iMeter = iMeter + dtMeter.Rows.Count;
                }
            }

            TableCell cell = new TableCell();

            Label lbBuilding = new Label();
            lbBuilding.Text = dtBuilding.Rows[0]["_name"].ToString();
            Label lbFloor = new Label();
            lbFloor.Text = "樓層數 : " + dtFloor.Rows.Count;
            Label lbRoom = new Label();
            lbRoom.Text = "寢室數 : " + iRoomCnt;
            Label lbMeter = new Label();
            lbMeter.Text = "電表數 : " + iMeter;
            Button btnSynMeter = new Button();
            btnSynMeter.Text = "電表時間同步";
            btnSynMeter.OnClientClick = "if (confirm('確定要同步此大樓的所有電錶時間？') == false) {return false;}";
            btnSynMeter.Click += new System.EventHandler(this.btnSynMeterClick);
            btnSynMeter.CommandArgument = strID;

            Button btnSynBuilding = new Button();
            btnSynBuilding.Text = "大樓電表歸零";
            btnSynBuilding.Click += new System.EventHandler(this.btnSynBuildingClick);
            btnSynBuilding.CommandArgument = strID + "," + i + "," + j;

            Table tb1 = new Table();
            tb1.Width = 140;
            
            TableRow tbr1=new TableRow();
            tbr1.BackColor = Color.LightSkyBlue;
            TableRow tbr2 = new TableRow();
            TableRow tbr3 = new TableRow();
            TableRow tbr4 = new TableRow();
            TableRow tbr5 = new TableRow();
            TableRow tbr6 = new TableRow();

            TableCell tbc1 = new TableCell();
            tbc1.Controls.Add(lbBuilding);
            tbc1.HorizontalAlign = HorizontalAlign.Center;
            TableCell tbc2 = new TableCell();
            tbc2.Controls.Add(lbFloor);
            TableCell tbc3 = new TableCell();
            tbc3.Controls.Add(lbRoom);
            TableCell tbc4 = new TableCell();
            tbc4.Controls.Add(lbMeter); 
            TableCell tbc5 = new TableCell();
            tbc5.Controls.Add(btnSynMeter);
            tbc5.HorizontalAlign = HorizontalAlign.Center;
            TableCell tbc6 = new TableCell();
            tbc6.Controls.Add(btnSynBuilding);
            tbc6.HorizontalAlign = HorizontalAlign.Center;

            tbr1.Cells.Add(tbc1);
            tbr2.Cells.Add(tbc2);
            tbr3.Cells.Add(tbc3);
            tbr4.Cells.Add(tbc4);
            tbr5.Cells.Add(tbc5);
            tbr6.Cells.Add(tbc6);

            tb1.Rows.Add(tbr1);
            tb1.Rows.Add(tbr2);
            tb1.Rows.Add(tbr3);
            tb1.Rows.Add(tbr4);
            tb1.Rows.Add(tbr5);
            tb1.Rows.Add(tbr6);

            tb1.BorderWidth = 2;

            cell.Controls.Add(tb1);

            return cell;
        }

        private void btnSynMeterClick(object sender, System.EventArgs e)
        {
            Button btnSender = (Button)sender;
            string strID = btnSender.CommandArgument;

            DataTable dtLog = (DataTable)Session["dtOrg"];
            dtLog.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtLog = dtLog.DefaultView.ToTable();

            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有修改設定的權限！')", true);
                return;
            }

            try
            {
                DataTable dtOrg = (DataTable)Session["dtOrg"];
                DataTable dtDevice = DBAPI.getDeviceTable("1");
                DataTable dtTag = DBAPI.getTagTable("1");

                DataTable dtFloor=dtOrg.Copy();
                DataTable dtRoom = dtOrg.Copy();

                dtFloor.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
                dtFloor = dtFloor.DefaultView.ToTable();

                string strErrMsg = "";

                if (dtFloor != null && dtFloor.Rows.Count > 0)
                {
                    for (int nFloor = 0; nFloor < dtFloor.Rows.Count; nFloor++)
                    {
                        dtRoom.DefaultView.RowFilter = "_parent_id ='" + dtFloor.Rows[nFloor]["_id"].ToString() + "'";
                        dtRoom = dtRoom.DefaultView.ToTable();
                        if (dtRoom != null && dtRoom.Rows.Count > 0)
                        {
                            for (int nRoom = 0; nRoom < dtRoom.Rows.Count; nRoom++)
                            {
                                DataTable dtMeter = dtDevice.Copy();
                                dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[nRoom]["_id"].ToString() + "'";
                                dtMeter = dtMeter.DefaultView.ToTable();

                                if (dtMeter != null && dtMeter.Rows.Count > 0)
                                {

                                    int intControlID = int.Parse(dtMeter.Rows[0]["_controller_id"].ToString());
                                    int intDeviceID = int.Parse(dtMeter.Rows[0]["_id"].ToString());

                                    DataTable dtTagCopy = dtTag.Copy();
                                    dtTagCopy.DefaultView.RowFilter = "_controller_id ='" + intControlID + "' and _device_id='" + intDeviceID + "'";
                                    dtTagCopy = dtTagCopy.DefaultView.ToTable();

                                    if (dtTagCopy != null && dtTagCopy.Rows.Count > 0)
                                    {
                                        int intYMTagID = 0;
                                        int intDHTagID = 0;
                                        int intMSTagID = 0;
                                        for (int i = 0; i < dtTagCopy.Rows.Count; i++)
                                        {
                                            switch (dtTagCopy.Rows[i]["_name"].ToString())
                                            {
                                                case "年月設定":
                                                    intYMTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                                    break;
                                                case "日時設定":
                                                    intDHTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                                    break;
                                                case "分秒設定":
                                                    intMSTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                                    break;
                                            }
                                        }

                                        DateTime dtNow = DateTime.Now;

                                        string strNow = dtNow.ToString("yyyy/MM/dd HH:mm:ss");

                                        string strYM = strNow.Substring(2, 2) + strNow.Substring(5, 2);
                                        string strDH = strNow.Substring(8, 2) + strNow.Substring(11, 2);
                                        string strMS = strNow.Substring(14, 2) + strNow.Substring(17, 2);
                                        int intYM = Convert.ToInt32(strYM, 16);
                                        int intDH = Convert.ToInt32(strDH, 16);
                                        int intMS = Convert.ToInt32(strMS, 16);

                                        Boolean blnResultYM = WSAPI.SetTagValue(int.Parse(dtTagCopy.Rows[0]["_device_id"].ToString()), intYMTagID, intYM);
                                        Boolean blnResultDH = WSAPI.SetTagValue(int.Parse(dtTagCopy.Rows[0]["_device_id"].ToString()), intDHTagID, intDH);
                                        Boolean blnResultMS = WSAPI.SetTagValue(int.Parse(dtTagCopy.Rows[0]["_device_id"].ToString()), intMSTagID, intMS);

                                        if (blnResultYM && blnResultDH && blnResultMS)
                                        {
                                            
                                        }
                                        else
                                        {
                                            strErrMsg = strErrMsg + dtMeter.Rows[0]["_desc"].ToString() + "//";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "大樓名稱：" + dtLog.Rows[0]["_name"].ToString();

                if (strErrMsg == "")
                {
                    new DBAccess().addEventLog(strAccount, strIP, 101, strMemo, "1", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶時間同步成功！')", true);
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, 101, strMemo + "//以下電錶同步失敗：" + strErrMsg, "0", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶時間同步失敗！以下電錶同步失敗" + strErrMsg + "')", true);
                }


            }
            catch
            {
                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "大樓名稱：" + dtLog.Rows[0]["_name"].ToString();
                new DBAccess().addEventLog(strAccount, strIP, 101, strMemo, "0", int.Parse(strID));

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶時間同步失敗！')", true);
            }
        }

        private void btnSynBuildingClick(object sender, System.EventArgs e)
        {
            divComfirm.Visible = true;
            Button btnSender = (Button)sender;
            string strArg = btnSender.CommandArgument;
            string[] strtemp = strArg.Split(',');
            int intID = int.Parse(strtemp[0]);
            int nRow = int.Parse(strtemp[1]);
            int nCol = int.Parse(strtemp[2]);
            int intTop = 80 + nRow * 150;
            int intLeft = 10 + nCol * 145;
            string strTop = intTop.ToString();
            string strLeft = intLeft.ToString();

            divComfirm.Style.Value = "position:absolute;left:" + strLeft + "px; top:" + strTop + "px; width:218px; height:114px; background-color:#ddeeff;";
            divComfirm.Visible = true;

            btnConfirm.CommandArgument = intID.ToString();

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            divComfirm.Visible = false;
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            Button btnSender = (Button)sender;
            string strID = btnSender.CommandArgument;

            DataTable dtLog = (DataTable)Session["dtOrg"];
            dtLog.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtLog = dtLog.DefaultView.ToTable();

            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有修改設定的權限！')", true);
                return;
            }

            try
            {
                DataTable dtOrg = (DataTable)Session["dtOrg"];
                DataTable dtDevice = DBAPI.getDeviceTable("1");
                DataTable dtTag = DBAPI.getTagTable("1");

                DataTable dtFloor = dtOrg.Copy();
                DataTable dtRoom = dtOrg.Copy();

                

                dtFloor.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
                dtFloor = dtFloor.DefaultView.ToTable();

                string strErrMsg = "";

                if (dtFloor != null && dtFloor.Rows.Count > 0)
                {
                    for (int nFloor = 0; nFloor < dtFloor.Rows.Count; nFloor++)
                    {
                        dtRoom.DefaultView.RowFilter = "_parent_id ='" + dtFloor.Rows[nFloor]["_id"].ToString() + "'";
                        dtRoom = dtRoom.DefaultView.ToTable();
                        if (dtRoom != null && dtRoom.Rows.Count > 0)
                        {
                            for (int nRoom = 0; nRoom < dtRoom.Rows.Count; nRoom++)
                            {
                                DataTable dtMeter = dtDevice.Copy();
                                dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[nRoom]["_id"].ToString() + "'";
                                dtMeter = dtMeter.DefaultView.ToTable();

                                

                                if (dtMeter != null && dtMeter.Rows.Count > 0)
                                {
                                    int intControlID = int.Parse(dtMeter.Rows[0]["_controller_id"].ToString());
                                    int intDeviceID = int.Parse(dtMeter.Rows[0]["_id"].ToString());

                                    DataTable dtTagCopy = dtTag.Copy();
                                    dtTagCopy.DefaultView.RowFilter = "_controller_id ='" + intControlID + "' and _device_id='" + intDeviceID + "'";
                                    dtTagCopy = dtTagCopy.DefaultView.ToTable();

                                    if (dtTagCopy != null && dtTagCopy.Rows.Count > 0)
                                    {
                                        int intRelyTagID = 0;
                                        for (int i = 0; i < dtTagCopy.Rows.Count; i++)
                                        {
                                            switch (dtTagCopy.Rows[i]["_name"].ToString())
                                            {
                                                case "電表Reset":
                                                    if (dtTagCopy.Rows[i]["_attribute"].ToString() == "AO")
                                                        intRelyTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                                    break;
                                            }
                                        }

                                        int intReset = 26214;

                                        Boolean blnResult = WSAPI.SetTagValue(int.Parse(dtTagCopy.Rows[0]["_device_id"].ToString()), intRelyTagID, intReset);
                                        if (blnResult == false)
                                        {
                                            strErrMsg = strErrMsg + dtMeter.Rows[0]["_desc"].ToString() + "//";
                                        }

                                    }
                                }
                            }
                        }
                    }
                }

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "大樓名稱：" + dtLog.Rows[0]["_name"].ToString();

                if (strErrMsg == "")
                {
                    new DBAccess().addEventLog(strAccount, strIP, 102, strMemo, "1", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶歸零成功！')", true);
                    divComfirm.Visible = false;
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, 102, strMemo + "//以下電錶歸零失敗：" + strErrMsg, "0", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶歸零失敗！以下電錶歸零失敗" + strErrMsg + "')", true);
                }


            }
            catch
            {
                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "大樓名稱：" + dtLog.Rows[0]["_name"].ToString();
                new DBAccess().addEventLog(strAccount, strIP, 102, strMemo, "0", int.Parse(strID));

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶歸零失敗！')", true);
            }

        }
    }
}